import { initInstructAddressEdit, saveInstructAddressEdit } from "../../../../service/api/api-instruct-address";
import Message from 'tdesign-miniprogram/message/index';
import Toast from 'tdesign-miniprogram/toast/index';
// pages/instruct/editor/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentUser: {},//当前用户
    access: {} as any,// 当前用户权限
    addressId: '',//编辑的通讯录的id
    addressName: '',//通讯录名称
    purpleList: [],//通讯录列表（备份）
    fabButton: {
      theme: "light"
    },//取消按钮配置
    selectIds: [],//选中的ids
    searchPurpleList: [],//搜索用的列表
    contactIds: [""],//已选择的id

    collapseOpenSelected: [],//控制 折叠面板 -  已选中的
    searchSelectedValue: '',//搜索框已选中列表
    selectedContacts: [],//已选中的用户列表

    collapseOpenUnchecked: [],//控制 折叠面板 -  未选中的
    searchUncheckedValue: '',//搜索框未选中列表
    uncheckedAccounts: [],//未选中用户的列表


  },
  //选择通讯录
  onChangeSelect(e) {
    this.setData({
      selectIds: e.detail.value
    })
  },

  /**
   *  控制 折叠面板 -  已选中的
   * @param e 
   */
  onHandleCollapseOpenSelectedChange(e) {

    this.setData({
      collapseOpenSelected: e.detail.value,
    });
  },
  /**
   *  控制 折叠面板 -  未选中的
   * @param e 
   */
  onHandleCollapseOpenUncheckedChange(e) {
    this.setData({
      collapseOpenUnchecked: e.detail.value,
    });
  },

  /**
   * 搜索 已选中 列表 
   * @param e 
   */
  onSearchSelectedChange(e) {
    var value = e.detail.value

    if (value == "") { // 输入框的值为空时，显示全部数据
      const selectedContacts = this.data.selectedContacts.map(item => {
        item.show = true;
        return item;
      })
      this.setData({
        selectedContacts: selectedContacts
      })
    } else {

      const searchSelectedContacts = this.data.selectedContacts.map(item => {
        let accountName = item.accountName ? item.accountName : ''
        let accountPhone = item.accountPhone ? item.accountPhone : ''
        let organizationName = item.organizationName ? item.organizationName : ''
        if (accountName.includes(value) || accountPhone.includes(value) || organizationName.includes(value)) {
          item.show = true
          return item;
        } else {
          item.show = false
          return item;
        }
      })

      this.setData({
        selectedContacts: searchSelectedContacts
      })
    }
  },

  onSearchSelectedClear(e) {
    const selectedContacts = this.data.selectedContacts.map(item => {
      item.show = true;
      return item;
    })

    this.setData({
      selectedContacts: selectedContacts
    })
  },

  /**
   * 搜索 未选中 列表 
   * @param e 
   */
  onSearchUncheckedChange(e) {
    var value = e.detail.value
    if (value == "") { // 输入框的值为空时，显示全部数据
      const uncheckedAccounts = this.data.uncheckedAccounts.map(item => {
        item.show = true;
        return item;
      })

      this.setData({
        uncheckedAccounts: uncheckedAccounts
      })
    } else {
      const searchUncheckedAccounts = this.data.uncheckedAccounts.map(item => {
        let accountName = item.accountName ? item.accountName : ''
        let accountPhone = item.accountPhone ? item.accountPhone : ''
        let organizationName = item.organizationName ? item.organizationName : ''
        if (accountName.includes(value) || accountPhone.includes(value) || organizationName.includes(value)) {
          item.show = true
          return item;
        } else {
          item.show = false
          return item;
        }
      })
      this.setData({
        uncheckedAccounts: searchUncheckedAccounts
      })
    }


  },

  /**
 * 搜索 未选中 列表 
 * @param e 
 */
  onSearchUncheckedClear(e) {
    const uncheckedAccounts = this.data.uncheckedAccounts.map(item => {
      item.show = true;
      return item;
    })

    this.setData({
      uncheckedAccounts: uncheckedAccounts
    })
  },

  /**
   * 点击 移除 通讯录
   * @param e 
   */
  onClickRemoveAddress(e) {
    var value = e.currentTarget.dataset.id
    const removeAccount = this.data.selectedContacts.find(item => item.id === value);
    const selectedContacts = this.data.selectedContacts.filter(item => item.id != value)
    this.setData({
      uncheckedAccounts: [...this.data.uncheckedAccounts, removeAccount],
      selectedContacts: selectedContacts
    })
  },

  /**
 * 点击 添加 通讯录
 * @param e 
 */
  onClickAddAddress(e) {
    var value = e.currentTarget.dataset.id

    const addAccount = this.data.uncheckedAccounts.find(item => item.id === value);
    const uncheckedAccounts = this.data.uncheckedAccounts.filter(item => item.id != value)
    this.setData({
      uncheckedAccounts: uncheckedAccounts,
      selectedContacts: [...this.data.selectedContacts, addAccount]
    })
  },


  //点击确定提交表单
  async handleSubmit() {
    if (this.data.addressName === null) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请输入通讯录名称',
      });
    } else {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '提交中',
        direction: 'column',
        duration: 3000,
        preventScrollThrough: true,
        theme: 'loading',
      });
      getApp().preventActive(async () => {
        const response = await saveInstructAddressEdit({
          combineIds: this.data.selectedContacts.map(item => item.id),
          id: this.data.addressId,
          name: this.data.addressName,
        });
        if (response.code === 0) {
          wx.showToast({
            title: "添加成功",
            icon: "success"
          })
          this.handleCancle()
        }
      })
    }
  },
  //取消编辑
  handleCancle() {
    wx.navigateBack({
      delta: 1
    })
  },

  //输入标题
  onInstructInput(e) {
    this.setData({
      addressName: e.detail.value
    })
  },
  //加载通讯录列表
  async onloadPurpleList(id) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    const response = await initInstructAddressEdit({ id });
    if (response.code === 0) {
      const contactIds = response.data.contactIds
      const accounts = response.data.accounts.map(item => {
        item.show = true;
        return item;
      })
      //已选中的用户列表
      const selectedAccounts = accounts.filter(item => {
        return contactIds.includes(item.id)
      })
      //未选中的用户列表
      const unSelectedAccounts = accounts.filter(item => {
        return !contactIds.includes(item.id)
      })
      this.setData({
        addressId: response.data.id,
        addressName: response.data.name,
        selectedContacts: selectedAccounts,
        uncheckedAccounts: unSelectedAccounts,
      })
      wx.hideLoading()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: { id: any; }) {
    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      currentUser,
      addressId: options.id
    })
    if (options.id) {
      wx.setNavigationBarTitle({
        title: "编辑通讯录"
      })
    }
    this.onloadPurpleList(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})